#!/bin/sh /etc/rc.common
# Copyright (C) 2009-2011 OpenWrt.org

START=80

CFG=/var/etc/rinetd.conf

common_add() {
	local cfg="$1"
	local logfile logcommon allow deny match

	config_get      logfile   "$cfg" logfile
	config_get_bool logcommon "$cfg" logcommon 0

	[ -n "$logfile" ] && {
		echo "logfile $logfile" >> $CFG
		[ "$logcommon" -gt 0 ] && echo "logcommon" >> $CFG
	}

	config_get allow "$cfg" allow
	config_get deny  "$cfg" deny

	for match in $allow; do
		echo "allow $match" >> $CFG
	done

	for match in $deny; do
		echo "deny $match" >> $CFG
	done
}

forward_add() {
	local cfg="$1"
	local bindaddr bindport connaddr connport

	config_get bindaddr "$cfg" bindaddress
	config_get bindport "$cfg" bindport
	config_get connaddr "$cfg" connectaddress
	config_get connport "$cfg" connectport

	[ -n "$bindaddr" ] && [ -n "$connaddr" ] && \
	[ -n "$bindport" ] && [ -n "$connport" ] && \
		echo "$bindaddr $bindport $connaddr $connport" >> $CFG
}

start() {
	mkdir -m 0755 -p /var/etc
	mkdir -m 0755 -p /var/run
	
	echo "# This file is autogenerated, check /etc/config/rinetd" > $CFG
	config_load 'rinetd'
	config_foreach common_add 'common'
	config_foreach forward_add 'forwarding'

	service_start /usr/sbin/rinetd -c $CFG
}

stop() {
	service_stop /usr/sbin/rinetd
}

reload() {
	service_reload /usr/sbin/rinetd
}
